package com.online_video.servlet.client;

import com.google.gson.Gson;
import com.online_video.entity.History;
import com.online_video.entity.User;
import com.online_video.entity.Video;
import com.online_video.service.HistoryService;
import com.online_video.service.VideoService;
import com.online_video.service.impl.HistoryServiceImpl;
import com.online_video.service.impl.VideoServiceImpl;
import com.online_video.servlet.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 黄金星
 * @Date: 2022/03/24/下午8:54
 * @Description:
 */
@WebServlet("/client/history.do")
public class HistoryServlet extends BaseServlet {
    HistoryService historyService = new HistoryServiceImpl();
    VideoService videoService = new VideoServiceImpl();

    /**
     * 由生成的历史记录的vid字符串生成当前历史记录
     * @param request
     * @param response
     * @throws IOException
     */
    public void insert(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("vid");
        String cookieValue = buildCookie(id, request);
        Cookie cookie = new Cookie("videoHistory", cookieValue);
        cookie.setPath("/online_video");
        //保存一周
        cookie.setMaxAge(60*60*24*7);
        /*点击当前视频生成cookie子符串*/
        response.addCookie(cookie);
        Gson gson = new Gson();
        String toJson = gson.toJson("1");
        response.getWriter().write(toJson);
    }

    public void showHistory(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("videoHistory")){
                Cookie cookie = cookies[i];
                /*将cookie字符串转为video的list返回*/
                LinkedList<String> videoList = new LinkedList(Arrays.asList(cookie.getValue().split("\\$")));
                List<Video> list = new ArrayList<>();
                for (int j = 0; j < videoList.size(); j++) {
                    Integer vid = Integer.parseInt(videoList.get(j));
                    Video video = videoService.queryByVid(vid);
                    list.add(video);
                }
                Gson gson = new Gson();
                String toJson = gson.toJson(list);
                response.getWriter().write(toJson);
            }
        }
    }

    /*构建一个保存当前视频vid的字符串 保存在cookie中*/
    private String buildCookie(String id, HttpServletRequest request) {
        String videoHistory = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equals("videoHistory")){
                videoHistory = cookies[i].getValue();
            }
        }

        if (videoHistory == null){
            return id;
        }

        LinkedList<String> videoList = new LinkedList(Arrays.asList(videoHistory.split("\\$")));
//       只保存7条历史记录
        if (videoList.size()>7){
            videoList.removeLast();
        }else if (videoList.contains(id)){
            videoList.remove(id);
        }
        videoList.addFirst(id);

        StringBuffer stringBuffer = new StringBuffer();
        for (String idNode:videoList){
            stringBuffer.append(idNode+"$");
        }
        return  stringBuffer.deleteCharAt(stringBuffer.length()-1).toString();
    }
    /*删除当前选中的vid*/
    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String videoHistory = null;
        Integer vid = Integer.parseInt(request.getParameter("vid"));
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("videoHistory")){
               videoHistory = cookies[i].getValue();
            }
        }
        LinkedList<String> videoList = new LinkedList(Arrays.asList(videoHistory.split("\\$")));
        if (videoList.contains(vid+"")){
            videoList.remove(vid+"");
        }

        StringBuffer stringBuffer = new StringBuffer();
        for (String idNode:videoList){
            stringBuffer.append(idNode+"$");
        }
        String cookieValue =  stringBuffer.deleteCharAt(stringBuffer.length()-1).toString();

        Cookie cookie = new Cookie("videoHistory", cookieValue);
        cookie.setPath("/online_video");
        //保存一周
        cookie.setMaxAge(60*60*24*7);
        /*点击当前视频生成cookie子符串*/
        response.addCookie(cookie);
        response.sendRedirect("./history.jsp");
    }
}
